<template>
  <div>
    <yq-dialog
      v-model="visible"
      :allow-drag="false"
      title="高德地图"
      width="900px"
      top="5vh"
      append-to-body
      :show-confirm-cancel-button="false"
      custom-class="dialog-title-background"
      :before-close="handleCancel"
      @open="handleOpen"
    >
      <div style="margin-top: -20px;margin-bottom: 10px;">
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          @click="handleConfirm()"
        >确定</el-button>
        <el-button
          icon="el-icon-circle-close"
          class="pause-button"
          @click="handleCancel"
        >取消</el-button>
      </div>
      <splitpanes>
        <pane :size="60">
          <div class="amap-wrapper">
            <el-amap
              v-if="mapStatus"
              class="amap-box"
              :vid="'amap-vue'"
              :center="center"
              :zoom="zoom"
              :events="events"
              :map-style="mapStyle"
            >
              <!-- 点击显示标记 -->
              <el-amap-marker
                v-for="(marker, index) in markers"
                :key="marker.index"
                :position="marker.position"
                :icon="marker.icon"
                :title="marker.title"
                :events="marker.events"
                :visible="marker.visible"
                :draggable="marker.draggable"
                :vid="index"
              />
            </el-amap>
          </div>
        </pane>
        <pane :size="40">
          <div class="map-address">详细地址：{{ address }}</div>
          <div class="map-mark">
            <div class="mark-item">
              <span>经度</span>
              <el-input
                v-model="lng"
                style="width: 110px"
                placeholder="请输入经度"
                maxlength="20"
              />
            </div>
            <div
              style="margin-left: 10px"
              class="mark-item"
            >
              <span>纬度</span>
              <el-input
                v-model="lat"
                style="width: 110px"
                placeholder="请输入纬度"
                maxlength="20"
              />
            </div>
            <el-button
              type="primary"
              style="margin-left: 1.7px"
              @click="handelQuery"
            >查询</el-button>
          </div>
          <div class="input-search">
            <el-row>
              <el-col :span="21">
                <el-input
                  v-model="address"
                  placeholder="请输入搜索地址"
                />
              </el-col>
              <el-col :span="3">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="searchMap"
                />
              </el-col>
            </el-row>
          </div>
        </pane>
      </splitpanes>
    </yq-dialog>
  </div>
</template>

<script>
import { Splitpanes, Pane } from 'splitpanes'
import AMap from 'vue-amap'
let that = null
export default {
  name: 'Amap',
  components: {
    Splitpanes,
    Pane
  },
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    // normal（默认样式）、dark（深色样式）、light（浅色样式）、fresh(osm清新风格样式)
    mapStyle: {
      type: String,
      default: 'normal'
    },
    location: {
      type: String,
      default: '北京市东城区东华门街道天安门'
    }
  },
  data() {
    return {
      mapStatus: false,
      map: {
        address: '北京市东城区东华门街道天安门',
        lng: '',
        lat: ''
      },
      tishi: '',
      // 地图相关
      address: '北京市东城区东华门街道天安门', // 获取的位置
      zoom: 14, // 地图缩放
      center: [116.397424, 39.909084], // 初始中心
      lng: 0, // 经纬度
      lat: 0,
      loaded: false,
      markers: [], // 点击显示的标记默认的定位
      //  自动定位到当前位置
      plugin: [
        {
          timeout: 1000, // 超过10秒后停止定位
          panToLocation: true, // 定位成功后将定位到的位置作为地图中心点
          zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见
          pName: 'Geolocation',
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.address = result.formattedAddress
                  self.lng = result.position.lng
                  self.lat = result.position.lat
                  self.map.address = self.address
                  self.map.lng = self.lng
                  self.map.lat = self.lat
                  if (self.Nowlnglat[0] != null && self.Nowlnglat[1] != null) {
                    const Clnglat = self.Nowlnglat
                    self.center = Clnglat
                    self.markers = [{ position: Clnglat }]
                    const geocoder = new AMap.Geocoder({ radius: 1000 })
                    // 根据坐标获取位置  将经纬度 转换后成 地址信息 放在 输入框展示
                    geocoder.getAddress(Clnglat, function (status, result) {
                      if (status === 'complete' && result.info === 'OK') {
                        self.address = result.regeocode.formattedAddress
                        self.lng = self.Nowlnglat[0]
                        self.lat = self.Nowlnglat[1]
                        self.map.address = self.address
                        self.map.lng = self.lng
                        self.map.lat = self.lat
                      }
                    })
                  } else {
                    self.center = [self.lng, self.lat]
                    self.markers = [{ position: self.center }]
                  }
                  self.loaded = true
                  self.$nextTick()
                } else {
                  o.getCityInfo((status, result) => {
                    if (result && result.center) {
                      self.address = result.province + result.city
                      self.lng = result.center[0]
                      self.lat = result.center[1]
                      self.map.address = self.address
                      self.map.lng = self.lng
                      self.map.lat = self.lat
                      if (self.Nowlnglat[0] != null && self.Nowlnglat[1] != null) {
                        const Clnglat = self.Nowlnglat
                        self.center = Clnglat
                        self.markers = [{ position: Clnglat }]
                        const geocoder = new AMap.Geocoder({ radius: 1000 })
                        // 根据坐标获取位置  将经纬度 转换后成 地址信息 放在 输入框展示
                        geocoder.getAddress(Clnglat, function (status, result) {
                          if (status === 'complete' && result.info === 'OK') {
                            self.address = result.regeocode.formattedAddress
                            self.lng = self.Nowlnglat[0]
                            self.lat = self.Nowlnglat[1]
                            self.map.address = self.address
                            self.map.lng = self.lng
                            self.map.lat = self.lat
                          }
                        })
                      } else {
                        self.center = result.center
                        self.markers = [{ position: self.center }]
                      }
                      self.loaded = true
                      self.$nextTick()
                    }
                  })
                }
              })
            }
          }
        }
      ],
      // 点击地图获取当前位置并显示标记
      events: {
        click(e) {
          if (!that) return
          const self = this
          that.lng = parseFloat(e.lnglat.lng)
          that.lat = parseFloat(e.lnglat.lat)
          self.map.lng = parseFloat(e.lnglat.lng)
          self.map.lat = parseFloat(e.lnglat.lat)
          self.center = [parseFloat(e.lnglat.lng), parseFloat(e.lnglat.lat)]
          self.loaded = true
          self.markers = [{
            position: self.center
          }]
          var geocoder
          AMap.plugin('AMap.Geocoder', function () {
            geocoder = new AMap.Geocoder({
              radius: 1000
            })
          })
          function regeoCode() {
            var lnglat = [parseFloat(e.lnglat.lng), parseFloat(e.lnglat.lat)]
            geocoder.getAddress(lnglat, function (status, result) {
              if (status === 'complete' && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.map.address = self.address
                that.address = result.regeocode.formattedAddress
                that.center = [e.lnglat.lng, e.lnglat.lat]
                that.markers = [{
                  position: that.center
                }]
              } else {
                self.address = undefined
                self.lng = undefined
                self.lat = undefined
                that.address = undefined
                that.lng = undefined
                that.lat = undefined
                self.$message({
                  type: 'error',
                  message: '根据经纬度查询地址失败'
                })
              }
            })
          }
          regeoCode()
        }
      }
    }
  },
  methods: {
    handleOpen() {
      that = this
      that.mapStatus = true
      if (that.location) {
        that.address = this.location
        that.map.address = this.location
      } else {
        that.address = '北京市东城区东华门街道天安门'
        that.map.address = '北京市东城区东华门街道天安门'
      }
      that.searchMap()
    },
    handleConfirm() {
      const location = {
        address: this.address,
        longitude: this.lng,
        latitude: this.lat
      }
      this.$emit('getLocation', location)
      this.setVisible()
    },
    handleCancel() {
      this.setVisible()
    },
    setVisible() {
      this.mapStatus = false
      this.$emit('update:visible', false)
    },
    searchMap() {
      const that = this
      const address = this.address
      that.map.address = that.address
      var geocoder
      AMap.plugin('AMap.Geocoder', function () {
        geocoder = new AMap.Geocoder({
          radius: 1000
        })
      })
      geocoder.getLocation(address, function (status, result) {
        if (status === 'complete' && result.geocodes.length) {
          var lnglat = result.geocodes[0].location
          that.center = [lnglat.lng, lnglat.lat]
          that.lng = lnglat.lng
          that.lat = lnglat.lat
          that.markers = [{
            position: that.center
          }]
          that.map.lng = that.lng
          that.map.lat = that.lat
        } else {
          that.address = undefined
          that.lng = undefined
          that.lat = undefined
          that.$message({
            type: 'error',
            message: '根据地址查询位置失败'
          })
        }
      })
    },
    handelQuery() {
      const self = this
      self.map.lng = parseFloat(self.lng)
      self.map.lat = parseFloat(self.lat)
      self.center = [parseFloat(self.lng), parseFloat(self.lat)]
      self.loaded = true
      self.markers = [{
        position: self.center
      }]
      var geocoder
      AMap.plugin('AMap.Geocoder', function () {
        geocoder = new AMap.Geocoder({
          radius: 1000
        })
      })
      // var marker = new AMap.Marker();
      function regeoCode() {
        var lnglat = [parseFloat(self.lng), parseFloat(self.lat)]
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            self.address = result.regeocode.formattedAddress
            self.map.address = self.address
          } else {
            self.address = undefined
            self.lng = undefined
            self.lat = undefined
            self.$message({
              type: 'error',
              message: '根据经纬度查询地址失败'
            })
          }
        })
      }
      regeoCode()
    }
  }
}
</script>
<style lang="scss" scoped>
.splitpanes {
  display: flex;
  width: 100%;
  height: 100%;
}
.amap-wrapper {
  width: 500px;
  height: 500px;
}
.map-address {
  font-size: 14px;
  font-weight: 800;
}
.map-mark {
  display: flex;
  flex-direction: row;
  margin-top: 20px;
  .mark-item {
    display: flex;
    align-items: center;
  }
}
.input-search {
  margin-top: 20px;
}
</style>
